package com.gensdai.leliang.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.classic.common.MultipleStatusView;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.ProductDetail;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.common.adapter.TypeProductAdapterRec;
import com.gensdai.leliang.common.bean.BrandListBean;
import com.gensdai.leliang.common.bean.CategoryBean;
import com.gensdai.leliang.common.clickinterface.OnProductClickListener;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.view.KeyRadioGroupV1;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 内层分类的fragment
 */
public class ContentTypeFragment extends BaseFragment {

    public static final int HOT_0 = 0x1110;
    public static final int HOT_1 = 1;
    public static final int HOT_2 = 2;
    public static final int HOT_3 = 3;
    public static final int HOT_4 = 4;
    public static final int HOT_5 = 5;
    public static final int HOT_6 = 6;

    Unbinder unbinder;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.scrollView)
    ScrollView scrollView;

    // TODO: Rename and change types of parameters


    List<Integer> ids;
    @BindView(R.id.productList)
    RecyclerView productList;

    //recyclerview on delegateAdapter
    DelegateAdapter delegateAdapter;
    //adapter list
    List<DelegateAdapter.Adapter> adapters;
    @BindView(R.id.type_multiplestatusview)
    MultipleStatusView typeMultiplestatusview;

    private int extid = HOT_0;

    public static ContentTypeFragment NewInstance(int id) {
        Bundle args = new Bundle();
        args.putInt("extid", id);
        ContentTypeFragment fragment = new ContentTypeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public ContentTypeFragment() {
        // Required empty public constructor

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            extid = getArguments().getInt("extid", HOT_0);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content_type, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());
        productList.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        productList.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);
        delegateAdapter = new DelegateAdapter(layoutManager, false);

        productList.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();

        //radio group添加选择事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                Log.e("onCheckedChanged", checkedId + "");
                initDataview(checkedId);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        rightAdapter = new TypeRightListAdapter(getActivity());
//        rightType.setAdapter(rightAdapter);


        //设置重试视图点击事件
        typeMultiplestatusview.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDataview(currentCheckId);
            }
        });



        getCategory();
    }

    public void getCategory() {
        Map<String, String> params = new HashMap<>();
        params.put("clientType", AppApplication.ClientType);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().QUERYALLCATEGORY(params))
                .compose(this.<BaseParseList<CategoryBean>>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserverList<CategoryBean>(getActivity()) {
                    @Override
                    public void onHandleSuccess(List<CategoryBean> c) {
                        initListType(c);
                    }

                    @Override
                    public void onHandleError(int code, String message) {

                    }
                });
    }

    int checkid = 0;
    private void initListType(List<CategoryBean> t) {
        //初始化左边分类

//        List<CategoryBean> menu = new ArrayList<>();
//        CategoryBean remai = new CategoryBean();
//        remai.categoryNo = HOT_0;
//        remai.name = getString(R.string.home_hot);
//
//        //初始化menu菜单栏
//        menu = new ArrayList<>();
//        CategoryBean baobao = new CategoryBean();
//        baobao.categoryNo = ContentTypeFragment.HOT_1;
//        baobao.name = (getString(R.string.home_yuntong));
//
//
//        CategoryBean wanju = new CategoryBean();
//        wanju.categoryNo = ContentTypeFragment.HOT_2;
//        wanju.name = getString(R.string.home_nongchanp);
//
//        CategoryBean yingtong = new CategoryBean();
//        yingtong.categoryNo = ContentTypeFragment.HOT_3;
//        yingtong.name = getString(R.string.home_yizhiwanju);
//
//
//        CategoryBean lema = new CategoryBean();
//        lema.categoryNo = ContentTypeFragment.HOT_4;
//        lema.name = getString(R.string.home_riyongpn);
//
//        CategoryBean nongchanp = new CategoryBean();
//        nongchanp.categoryNo = ContentTypeFragment.HOT_5;
//        nongchanp.name = getString(R.string.home_meizhuang);
//
//        CategoryBean riyongp = new CategoryBean();
//        riyongp.categoryNo = ContentTypeFragment.HOT_6;
//        riyongp.name = getString(R.string.home_hufu);
//
//        menu.add(remai);
//        menu.add(baobao);
//        menu.add(wanju);
//        menu.add(yingtong);
//        menu.add(lema);
//        menu.add(nongchanp);
//        menu.add(riyongp);

//        adapter = new LeftTypeAdapter(getActivity());
//        leftType.setAdapter(adapter);
//        adapter.initAdd(menu);

        ids = new ArrayList<>();
        for (int i = 0; i < t.size(); i++) {
            CategoryBean me = t.get(i);
            RadioButton rabtn = new RadioButton(getActivity());
            rabtn.setId(me.categoryNo);
            rabtn.setText(me.name);
            rabtn.setBackgroundResource(R.drawable.radio_button);
            Bitmap a = null;
            rabtn.setButtonDrawable(new BitmapDrawable(a));
            rabtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
            rabtn.setTextColor(ContextCompat.getColorStateList(getActivity(), R.color.radio_text_color));
            rabtn.setGravity(Gravity.CENTER);
//            rabtn.setPadding(getResources().getDimensionPixelOffset(R.dimen.px22dp), getResources().getDimensionPixelOffset(R.dimen.px10dp), getResources().getDimensionPixelOffset(R.dimen.px10dp), 0);
//            rabtn.setPadding(getResources().getDimensionPixelOffset(R.dimen.px22dp), getResources().getDimensionPixelOffset(R.dimen.px10dp), getResources().getDimensionPixelOffset(R.dimen.px10dp), 0);
            rabtn.setLayoutParams(new KeyRadioGroupV1.LayoutParams(KeyRadioGroupV1.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen.bottom_tga_size)/*KeyRadioGroupV1.LayoutParams.WRAP_CONTENT*/));
            radioGroup.addView(rabtn);

            ids.add(rabtn.getId());

            if(i == 0){
                checkid = me.categoryNo;
            }

            if (me.categoryNo == (extid)) {
                checkid = me.categoryNo;
            }
        }



        ((RadioButton) radioGroup.findViewById(checkid)).setChecked(true);


        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.smoothScrollTo(0,radioGroup.findViewById(checkid).getTop());
            }
        });

    }

    public void updateRadioPosition(int exid) {
        Log.e("updateRadioPosition", exid + "");
        if (ids != null) {
            if(radioGroup.getChildCount() > 0){
                if(exid != HOT_0 && ids.contains(exid)){
                    if (radioGroup.getCheckedRadioButtonId() != exid) {
                        //解决点击后调用三次
                        scrollView.smoothScrollTo(0,radioGroup.findViewById(exid).getTop());
                        ((RadioButton) radioGroup.findViewById(exid)).setChecked(true);
                    }
                }else{
                    ((RadioButton) radioGroup.findViewById(ids.get(0))).setChecked(true);
                }
            }else{

            }
        }

    }

    Disposable oldDisposable;
    private int currentCheckId = 0;
    BaseObserverList obs;

    private void initDataview(int checkedId) {

        currentCheckId = checkedId;


        if (!BaseUtils.isNetworkAvailable(getActivity())) {
            //没有网络显示无网络
            typeMultiplestatusview.showNoNetwork();
            return;
        }


        String catNo = checkedId + "";
//        switch (checkedId) {
//            case HOT_0:
//                //点击热卖
//                catNo = "0";
//                break;
//            case HOT_1:
//                //点击孕童婴
//                catNo = "1";
//                break;
//            case HOT_2:
//                //点击益智玩具
//                catNo = "2";
//                break;
//            case HOT_3:
//                //点击农产品
//                catNo = "3";
//                break;
//            case HOT_4:
//                //点击日用品
//                catNo = "4";
//                break;
//            case HOT_5:
//                //点击美妆
//                catNo = "5";
//                break;
//            case HOT_6:
//                //点击护肤
//                catNo = "6";
//                break;
//        }


        Map<String, String> params = new HashMap<>();
        params.put("categoryNo", catNo);
//        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getFenleiList(params))
//                .compose(this.<BaseParseList<ProductInfo>>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        //开始监听前的处理，一般用于显示dialog什么的
//////                        if (hud != null) {
//////                            hud.show();
//////                        }
//                        typeMultiplestatusview.showLoading();
//                        Log.d("accept", "accept");
//                    }
//                })
//                .subscribe(new BaseObserverList<ProductInfo>(getActivity()) {
//                    @Override
//                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
//                        super.onSubscribe(d);
//                        Log.d("onSubscribe", "onSubscribe");
//                        if (oldDisposable != null) {
//                            oldDisposable.dispose();
//                        }
//                        oldDisposable = d;
//                    }
//
//                    @Override
//                    public void onHandleSuccess(List<ProductInfo> t) {
//                        //处理得到的数据
//                        initGridview(t);
//                    }
//
//                    @Override
//                    public void onHandleError(int code, String message) {
//
//                    }
//
//                    @Override
//                    public void onFailure(Throwable e) {
//                        super.onFailure(e);
//                        //异常处理
//                        e.printStackTrace();
//                        typeMultiplestatusview.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                typeMultiplestatusview.showError();
//                            }
//                        });
//                    }
//                });
        ApiService.getInstance(getActivity()).getFenleiList(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<BaseParseList<ProductInfo>>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        typeMultiplestatusview.showLoading();
                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseParseList<ProductInfo>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅 判断是否处于取消状态
                        boolean b = d.isDisposed();

                        if (oldDisposable != null) {
                            oldDisposable.dispose();
                        }
                        oldDisposable = d;


                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParseList<ProductInfo> s) {
                        //处理得到的数据
                        initGridview(s.data);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
                        typeMultiplestatusview.post(new Runnable() {
                            @Override
                            public void run() {
                                typeMultiplestatusview.showError();
                            }
                        });
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    private void initGridview(List<ProductInfo> list) {

        if (adapters != null) {
            adapters.clear();
            delegateAdapter.notifyDataSetChanged();
        }

        //当数据操作大于0的时候才填充recyclerview
        if (list != null && list.size() > 0) {
            GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
            layoutHelper.setPadding(getResources().getDimensionPixelOffset(R.dimen.px18dp), getResources().getDimensionPixelOffset(R.dimen.px10dp), getResources().getDimensionPixelOffset(R.dimen.px22dp), 0);
            layoutHelper.setAutoExpand(false);
//        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.white));
            //横间距
            layoutHelper.setHGap(getResources().getDimensionPixelSize(R.dimen.px4dp));
            //垂直间距
            layoutHelper.setVGap(getResources().getDimensionPixelSize(R.dimen.px4dp));
            if (adapters != null) {
                TypeProductAdapterRec typeProductAdapter = new TypeProductAdapterRec(getActivity(), layoutHelper, list);
                typeProductAdapter.setOnProductClicklistener(productClickListener);
                adapters.add(typeProductAdapter);
            }
            delegateAdapter.setAdapters(adapters);
            delegateAdapter.notifyDataSetChanged();


            typeMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    typeMultiplestatusview.showContent();
                }
            }, 500);
        } else {
            typeMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    typeMultiplestatusview.showEmpty();
                }
            }, 500);
        }
    }

    OnProductClickListener productClickListener = new OnProductClickListener<ProductInfo>() {
        @Override
        public void OnProductClick(ProductInfo info, int position) {
            startPorductInfo(info.getId());
        }
    };


    private void startPorductInfo(String pid) {
        Intent it = new Intent(getActivity(), ProductDetail.class);
        it.putExtra(ProductDetail.EXTRA_PID, pid/*"0063ed7e81b64fec8e0aa88212987639"*/);
        startActivity(it);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
